package com.komlin.msgpush;

import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.coloros.mcssdk.PushManager;
import com.coloros.mcssdk.callback.PushAdapter;
import com.coloros.mcssdk.callback.PushCallback;
import com.coloros.mcssdk.mode.ErrorCode;
import com.coloros.mcssdk.mode.SubscribeResult;
import com.komlin.msgpush.huaweipushmsg.agent.HMSAgent;
import com.komlin.msgpush.huaweipushmsg.agent.push.handler.GetTokenHandler;
import com.komlin.msgpush.interf.KomlinPushRevicer;
import com.vivo.push.IPushActionListener;
import com.vivo.push.PushClient;
import com.xiaomi.mipush.sdk.MiPushClient;

import java.util.List;

/**
 * @Author lifq
 * 创建时间： 2019/6/3 16:38
 * 包名： com.komlin.msgpush
 * 功能描述：
 **/
public class KomlinPushManager {

    public static String MANUFACTURER;
    public Application context;
    //小米
    private String xiaomiAppId;
    private String xiaomiAppKey;
    private String oppoAppKey;
    private String oppoAppSecret;
    private static int bager = 0;
    //单例模式
    private static KomlinPushManager instance = new KomlinPushManager();

    private KomlinPushManager() {

    }

    public static KomlinPushManager getInstance() {
        return instance;
    }

    public KomlinPushRevicer revicer;

    public static int getBager() {
        return bager;
    }

    public static void setBager(int bager) {
        KomlinPushManager.bager = bager;
    }

    //初始化推送服务
    public void initKomlinPushMsg(Application application, KomlinPushRevicer receiver) {
        context = application;
        this.revicer = receiver;
        init();
    }

    private void init() {
        //判断手机品牌，分别进行初始化操作
        MANUFACTURER = Build.MANUFACTURER.toLowerCase();
        Log.e("MyApplication", MANUFACTURER);

        //获取小米和oppo <meta-data>中的值
        ApplicationInfo applicationInfo;
        try {
            applicationInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
            Bundle bundle = applicationInfo.metaData;
            xiaomiAppId = changeValue(bundle.getString("xiaomi_app_id"));
            xiaomiAppKey = changeValue(bundle.getString("xiaomi_app_key"));
            oppoAppKey = bundle.getString("oppo_app_key");
            oppoAppSecret = bundle.getString("oppo_app_secret");
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        if (MANUFACTURER.contains("huawei")) {
            //华为推送初始化
            HMSAgent.init(context);
            getToken(context);
        } else if (MANUFACTURER.contains("oppo")) {
            //oppo推送初始化
            initOppoPush();
        } else if (MANUFACTURER.contains("vivo")) {
            //vivo推送初始化
            PushClient.getInstance(context).initialize();  //当需要打开推送服务时，调用以下代码
           /* PushClient.getInstance(context).turnOffPush(new IPushActionListener() {
                @Override
                public void onStateChanged(int i) {
                    Log.e("NPL", "vivo取消订阅::::");
                }
            });*/
            PushClient.getInstance(context).turnOnPush(new IPushActionListener() {
                @Override
                public void onStateChanged(int state) {
                    if (state == 0) {
                        String regId = PushClient.getInstance(context).getRegId();
                        revicer.onToken(regId);
                        Log.e("NPL", "vivo打开推送服务成功::::" + regId);
                    } else {
                        Log.e("NPL", "vivo消息推送失败");
                    }
                }
            });
        } else {
            //小米推送初始化
            if (shouldInit()) {
                //注册推送服务
                //注册成功后会向DemoMessageReceiver发送广播
                // 可以从DemoMessageReceiver的onCommandResult方法中MiPushCommandMessage对象参数中获取注册信息
                MiPushClient.registerPush(context, xiaomiAppId, xiaomiAppKey);
            }
        }
    }

    /**
     * 小米推送
     * 通过判断手机里的所有进程是否有这个App的进程
     * 从而判断该App是否有打开
     *
     * @return
     */
    private boolean shouldInit() {
        //通过ActivityManager我们可以获得系统里正在运行的activities
        //包括进程(Process)等、应用程序/包、服务(Service)、任务(Task)信息。
        ActivityManager am = ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE));
        List<ActivityManager.RunningAppProcessInfo> processInfos = am.getRunningAppProcesses();
        String mainProcessName = context.getPackageName();
        //获取本App的唯一标识
        int myPid = android.os.Process.myPid();
        //利用一个增强for循环取出手机里的所有进程
        for (ActivityManager.RunningAppProcessInfo info : processInfos) {
            //通过比较进程的唯一标识和包名判断进程里是否存在该App
            if (info.pid == myPid && mainProcessName.equals(info.processName)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 初始化OPPO推送
     */
    protected void initOppoPush() {
        //在执行Oppo推送注册之前，需要先判断当前平台是否支持Oppo推送
        if (PushManager.isSupportPush(context)) {
            Log.e("oppo消息推送服务", "context=" + context + "===oppoAppKey==" + oppoAppKey + "=oppoAppSecret=" + oppoAppSecret);
            //获取通知弹框
            try {
                PushManager.getInstance().register(context, oppoAppKey, oppoAppSecret, new PushAdapter() {
                    @Override
                    public void onRegister(int i, String registerId) {
                        Log.e("oppo消息推送服务", "注册成功，i == " + i + "registerId=" + registerId);
                        if (i == ErrorCode.SUCCESS) {
                            //注册成功
                            if (revicer != null) {
                                revicer.onToken(registerId);
                                Log.e("oppo消息推送服务", "注册成功，registerId=" + registerId);
//                        SP_Utils.saveString("oppoRegisterId",registerId);
                            }
                        } else {
                            //注册失败
                            Log.e("oppo消息推送服务", "注册失败");
                            PushManager.getInstance().getRegister();
                        }
                    }
                });
            } catch (Exception e) {
                Log.e("oppo消息推送服务", "注册失败ee" + e.toString());
            }
        }
    }

    /**
     * 初始化华为推送
     * 获取token | get push token
     *
     * @param context
     */
    private static void getToken(Application context) {
        HMSAgent.Push.getToken(new GetTokenHandler() {
            @Override
            public void onResult(int rtnCode) {
                //结果返回码,rtnCode == 0表示成功
                Log.d("get token: end code=", String.valueOf(rtnCode));
            }
        });
           /* new Thread() {
                @Override
                public void run() {
                    try {
                        // read from agconnect-services.json
                        String appId = AGConnectServicesConfig.fromContext(context).getString("client/app_id");
                        String token = HmsInstanceId.getInstance(context).getToken(appId, "HCM");
                        Log.i("TAG11", "get token:" + token);
                        if(!TextUtils.isEmpty(token)) {

                        }
                    } catch (ApiException e) {
                        Log.e("TAG11", "get token failed, " + e);
                    }
                }
            }.start();*/
    }

    public String changeValue(String value) {
        return value.substring(0, value.length() - 1);
    }

}
